import Taro, { Config } from '@tarojs/taro'
import { Button, Image, RichText, Text, View, Swiper, SwiperItem } from '@tarojs/components'
import './index.scss'
import '@/styles/common/goods-info.scss'
// import classNames from 'classnames'
import moment from '@/assets/js/moment.min'
import { filterGoodsInfo } from "@/utils/filter"
import { addCart } from '@/api/userApi'
import { infoById } from '@/api/productApi'
import { toCalcOrderPage, toCommentGoodsPage } from '@/utils/page_router'
import FyComponent from "@/components/common/goods"
import {
  NeedScore,
  SalePrice,
  GoodsNavbar,
  Loading,
  TitleOne,
  AvatarList,
  GoodsCarousel,
  GoodsOneList,
  ShareImage,
  CommentGoods,
  CommentGoodsTwo,
  GoodsSelect,
  BuyRecord,
  GoodsDiscount,
  GoodsFiveList,
  GoodsCommend, FyImg, GoodsCarouselTwo, PriceDescription
} from "@/components/index"
import GoodsFoot from "@/components/goods/goods-foot"
import UserBuyRecord from "@/components/user-buy-record/index"
import UserBuyRecordTwo from "@/components/user-buy-record/record-two/index"
import SeckillCountdown from "@/components/countdown/seckill";
import timeLimitExchange from "@/assets/images/time-limit-exchange.jpg";
import { getBrand, goodsScore } from "@/utils/storage";
import { getFilter, getUnit, shuffle } from "@/utils/utils";
import styles from "@/components/user-buy-record/index.module.scss";
import { getRollBuyRecord } from "@/api/commonApi";
import shareIcon from '@/assets/images/share-icon.png'
import ShareModal from '../share-modal/index'
import lodash from "@/utils/lodash";
import xfUtil from '@xfjs/xf-utils-vue'
import { PRODUCT_SALES_TEXT } from "@/config/file";
import ScrollTop from "@/components/scroll-top"

export default class Index extends FyComponent {
  config: Config = {
    navigationStyle: 'custom'
  }

  componentWillMount() {
    this.getGoodsInfo()
    this.getGoodsPage()
    this.getCommentPage()
    this.setState({
      duihuanbi: true,
    })
  }

  //  页面滚动触发事件的处理函数
  onPageScroll(e) {
    this.onScroll(e)
    if (e.scrollTop > 300) {
      this.setState({
        zhiding: true,
      })
    } else {
      this.setState({
        zhiding: false,
      })
    }
    if (e.scrollTop) {
      this.setState({
        duihuanbi: false,
      })
    } else {
      this.setState({
        duihuanbi: true,
      })
    }
  }

  //  获取商品详情
  getGoodsInfo() {
    const { params } = this.$router

    const end = moment().endOf('day').valueOf()
    const cur = Number(new Date())
    const time = Math.floor((end - cur) / 1000)
    infoById(params.id).then(res => {
      const { data } = res
      data.seconds = time
      data.timestamp = Number(new Date())
      this.setState({
        goodsInfo: filterGoodsInfo(data),
        comboList: data.skuDetail || [],
        goodsImages: data.images
      }, () => {
        this.setState({
          loadingStatus: false
        })
        setTimeout(() => {
          this.getNodeLocation()
        }, 200)
      })
    }).catch(() => {
      setTimeout(() => {
        Taro.navigateBack()
      }, 800)
    })
    getRollBuyRecord().then(({ data }) => {
      this.state.buyList = shuffle(data).map((item) => {
        item.time = Math.floor(Math.random() * 20 + 1)
        item.connectSnap['name'] = `${lodash.head(item.connectSnap['name'])}**`
        item.connectSnap['telephone'] = getFilter(item.connectSnap['telephone'], 3, 3, '*')
        return { name: item.connectSnap['name'], phone: item.connectSnap['telephone'], time: item.time }
      })
    })
  }

  //  显示选择商品
  setShowSelect(bool) {
    this.setState({
      showSelect: bool
    })
  }

  //  确认选择商品
  onConfirm(type, info, number) {
    if (type === 'cart') {
      addCart({ productId: info.productId, skuId: info.skuId, number }).then(() => {
        Taro.showToast({ title: '添加成功' })
      })
    } else {
      toCalcOrderPage({ cartList: [{ id: info.productId, skuId: info.skuId, number }] })
    }
    this.setState({
      showSelect: false
    })
  }

  // 分享
  shareProduct(event) {
    event.stopPropagation()
    this.setState({
      shareVisible: true
    })
  }

  changeShare(bool) {
    this.setState({
      shareVisible: bool
    })
  }

  showDuihuanbi() {
    this.setState({
      duihuanbi: true
    })
  }

  render() {
    const { buyList, opacity, nodeKey, nodeList, score, userInfo, shareVisible, goodsInfo, goodsList, showSelect, showShareImg, shareImg, commentRes, loadingStatus, zhiding, duihuanbi } = this.state
    return (<View className='goods-page'>
      <ScrollTop ref="ScrollTop" zhiding={zhiding} duihuanbi={duihuanbi} showDuihuanbi={this.showDuihuanbi.bind(this)} />
      {loadingStatus && <Loading />}
      {/*<GoodsNavbar opacity={opacity}>*/}
      {/*  <View className='node-list'>*/}
      {/*    {nodeList.map((item, key) => {*/}
      {/*      return (<View key={item.id} className={classNames('node-item f-g-5', nodeKey === key && 'node-item__active')} onClick={this.onSwitchNode.bind(this, item, key)}>{item.name}</View>)*/}
      {/*    })}*/}
      {/*    <View className='under-line' style={{ left: `calc(${nodeKey * percent}% + (${percent}% / 2))` }}/>*/}
      {/*  </View>*/}
      {/*</GoodsNavbar>*/}
      <GoodsNavbar opacity={opacity} nodeKey={nodeKey} nodeList={nodeList} onSwitchNode={this.onSwitchNode.bind(this)} />
      <View className='goods-scroll'>
        <View id='goods-info' className='goods-card'>
          <GoodsCarouselTwo goods={goodsInfo} />
          {/*<GoodsCarousel images={goodsInfo.images} video={{ url: goodsInfo.video, poster: goodsInfo.videoCoverImg }}/>*/}
          <View className='goods-activity'>
            <View className='activity-left d-f f-g-7'>
              {goodsScore(goodsInfo.needScore) && <View className='f-s-40'>{goodsInfo.needScore}{getBrand()}+</View>}
              <View className='f-s-38'>{Number(goodsInfo.salePrice)}元</View>
              {Number(goodsInfo.originPrice) > Number(goodsInfo.salePrice) && <s className='f-s-30 m-l-10'>￥{Number(goodsInfo.originPrice)}</s>}
            </View>
            {<View className='salesNumber d-f j-c-b'>
              {goodsInfo.salesNumber ? <View>{PRODUCT_SALES_TEXT} {getUnit(goodsInfo.salesNumber, '+')}</View> : <View></View>}
              {goodsScore(goodsInfo.needScore) && <View className='d-f'>
                {getBrand()}已省￥{Math.round(Number(goodsInfo.originPrice) - Number(goodsInfo.salePrice))}
              </View>}
            </View>}
          </View>
          {/*<View className='goods-activity d-f a-i-s'>*/}
          {/*  <View className='activity-left f-g-2 f-d-c'>*/}
          {/*    <Text className='left-title'>库存告急</Text>*/}
          {/*    <Text className='activity-desc p-t-10'>*/}
          {/*      {goodsInfo.limitNumber ? `每人限购 ${goodsInfo.limitNumber}${goodsInfo.unitName}` : '限时兑换'}*/}
          {/*    </Text>*/}
          {/*  </View>*/}
          {/*  <View className='activity-right f-g-8 f-d-c'>*/}
          {/*    <Text className='activity-desc p-b-10'>距结束</Text>*/}
          {/*    <SeckillCountdown seconds={goodsInfo.seconds}/>*/}
          {/*  </View>*/}
          {/*</View>*/}
          <View className='goods-head'>
            {/*<View className='d-f a-i-c j-c-b'>*/}
            {/*  <View className='price d-f a-i-b'>*/}
            {/*    <NeedScore goods={goodsInfo} priceSize={44} className='m-r-10'/>*/}
            {/*    <SalePrice goods={goodsInfo} priceSize={32}/>*/}
            {/*    /!*<View className='sale-price bnn-number'>*!/*/}
            {/*    /!*  /!*<Text className='price-unit'>￥</Text>*!/*!/*/}
            {/*    /!*  +{goodsInfo.salePrice}元*!/*/}
            {/*    /!*</View>*!/*/}
            {/*    {goodsInfo.originPrice * 100 > goodsInfo.salePrice * 100 && <View style="color: #333" className='origin-price bnn-number m-l-10'>￥{goodsInfo.originPrice}</View>}*/}
            {/*  </View>*/}
            {/*  <View className='user-like f-g-5'>*/}
            {/*    <Text className='like-icon bnn-icon m-r-10'>&#xe668;</Text>{goodsInfo.storeCount}人喜欢*/}
            {/*  </View>*/}
            {/*</View>*/}
            {/*<View className='goods-name'>
              <View>{goodsInfo.name}</View>
              <View className='share' onClick={this.shareProduct.bind(this)}>
                <FyImg src={shareIcon} className='share-icon'/>
                分享
              </View>
            </View>*/}
            {/*<View className='stock-box d-f a-i-c j-c-b'>*/}
            {/*  <View className=''>已兑换{goodsInfo.salesNumber}{goodsInfo.unitName}</View>*/}
            {/*  <View className='integral-save d-f a-i-c'>*/}
            {/*    <View className='save-icon bnn-icon'>&#xe6ac;</View>*/}
            {/*    <View className='save-box d-f f-d-c'>*/}
            {/*      <View className='save-text'>{getBrand()}已省</View>*/}
            {/*      <View className='save-price bnn-number'>{Math.round(goodsInfo.originPrice - goodsInfo.salePrice)}元</View>*/}
            {/*    </View>*/}
            {/*  </View>*/}
            {/*  /!*<View className=''>剩余库存{goodsInfo.stockNumber}{goodsInfo.unitName}</View>*!/*/}
            {/*</View>*/}
            {
              goodsInfo.tips && <View className='goods-tips'>
                <View className='tips-head'>推荐理由</View>
                <View>
                  {goodsInfo.tips.map(item => {
                    return <View>{item}</View>
                  })}
                </View>
              </View>
            }
            {/*<GoodsDiscount goods={goodsInfo} user={userInfo} className='m-t-30'/>*/}
            {/*{showMemberPrice(goodsInfo) && <View className='member-box d-f a-i-c j-c-b' onClick={() => toMemberOpenPage()}>*/}
            {/*  <View className='member-left d-f a-i-c'>*/}
            {/*    <Image src={vipImg} className='left-icon'/>*/}
            {/*    <View className='left-text'>会员价<Text className='member-price'>￥{goodsInfo.memberPrice}</Text>{goodsInfo.saveMoney ? `省￥${goodsInfo.saveMoney}` : ''}</View>*/}
            {/*  </View>*/}
            {/*  <View className='member-right d-f a-i-c'>*/}
            {/*    <View className='right-text'>{userInfo.isVip ? '' : '立即开通'}</View>*/}
            {/*    <View className='right-icon bnn-icon'>&#xe866;</View>*/}
            {/*  </View>*/}
            {/*</View>}*/}
            {/*<View className='sales-record d-f j-c-b'>*/}
            {/*  <AvatarList list={goodsInfo.salesReport && goodsInfo.salesReport.map(i => i.userInfo && i.userInfo.headImg)} showMore/>*/}
            {/*  /!*<View className='invite-btn d-f a-i-c bnn-number' hoverClass='hover-class--btn' onClick={this.showShareImg.bind(this)}>*!/*/}
            {/*  /!*  {goodsInfo.shareAmount ? `分享赚 ${goodsInfo.shareAmount} 元` : '分享给好友'}*!/*/}
            {/*  /!*</View>*!/*/}
            {/*</View>*/}
            {/*{<View className='tip-list d-f f-w-w'>*/}
            {/*  {goodsInfo.tips && goodsInfo.tips.map((str, k) => {*/}
            {/*    return (<View key={k} className='tip-item d-f a-i-c'>*/}
            {/*      <View className='bnn-icon tip-icon'>&#xe645;</View>*/}
            {/*      <View className='tip-text l-h-o'>{str}</View>*/}
            {/*    </View>)*/}
            {/*  })}*/}
            {/*</View>}*/}
          </View>
        </View>

        <View className='time-limit-exchange'>
          <FyImg style="margin-left:15px;" src={timeLimitExchange} />
        </View>

        <View className='m-b-10'>
          <UserBuyRecord buyList={buyList} info={goodsInfo} goBuy={this.setState.bind(this, { showSelect: 'buy' })} />
        </View>

        <View className='m-b-10'>
          {!xfUtil.isEmptyObject(goodsInfo) && <GoodsCommend score={goodsInfo.needScore} />}
        </View>

        {/* --------------------------------- 用户评论 --------------------------------- */}
        {commentRes.list && !!commentRes.list.length && <View id='goods-comment' className='goods-card goods-card__body comment-card'>
          <CommentGoodsTwo list={commentRes.list} info={goodsInfo} />
          {/*<View className='goods-card__head'>*/}
          {/*  <TitleOne>用户评论</TitleOne>*/}
          {/*</View>*/}
          {/*<View className='comment-list'>*/}
          {/*  {commentRes.list.map(info => {*/}
          {/*    return (<CommentGoodsTwo key={info.id} info={info} className='comment-item'/>)*/}
          {/*  })}*/}
          {/*  <View className='see-more f-g-5' onClick={() => toCommentGoodsPage(goodsInfo.id)}>查看更多好评（{commentRes.totalCount}）</View>*/}
          {/*</View>*/}
        </View>}

        <View className='goods-body'>
          {/* --------------------------------- 商品详情 --------------------------------- */}
          {goodsInfo.description && <View id='goods-desc' className='goods-card'>
            <View className='goods-card__head'>
              <TitleOne>商品详情</TitleOne>
            </View>
            <View className='rich-text-wrap goods-card__body'>
              <RichText nodes={goodsInfo.description} />
            </View>
          </View>}

          {/* --------------------------------- 商品推荐 --------------------------------- */}
          {/*<View id='goods-hot' className='goods-card'>*/}
          {/*  <View className='goods-card__head'>*/}
          {/*    <TitleOne>更多美好生活</TitleOne>*/}
          {/*  </View>*/}
          {/*  /!*<GoodsOneList list={goodsList}/>*!/*/}
          {/*  <GoodsFiveList list={goodsList}/>*/}
          {/*</View>*/}
        </View>
        <PriceDescription />
        <View className='goods-foot--height' />
      </View>

      <GoodsFoot
        menus={['home', 'service']}>
        {/*{!goodsInfo.disabled && <Button*/}
        {/*  className='goods-foot__btns-btn goods-foot__cart-btn xf-btn'*/}
        {/*  onClick={this.setState.bind(this, { showSelect: 'cart' })}>加入购物车</Button>}*/}
        <Button
          disabled={goodsInfo.disabled}
          className='goods-foot__btns-btn xf-btn xf-btn-primary'
          onClick={this.setState.bind(this, { showSelect: 'buy' })}>{goodsInfo.disabledText || goodsScore(goodsInfo.needScore) ?
            <View className="btn-box">
              <View className="submit-text">立即兑换</View>
              <View className="sub-text">兑换币即将到期</View>
            </View>
            : '立即抢购'}</Button>
      </GoodsFoot>

      <GoodsSelect goods={goodsInfo} isOpened={showSelect} onClose={this.setState.bind(this, { showSelect: false })} onConfirm={this.onConfirm.bind(this, showSelect)} />
      {/*<ShareImage isOpened={showShareImg} width={500} height={890} image={shareImg} onClose={this.showShareImg.bind(this, false)}/>*/}
      {/*<BuyRecord top={134}/>*/}
      <UserBuyRecordTwo buyList={buyList} top={90} />
      <ShareModal info={goodsInfo} show={shareVisible} onChange={this.changeShare.bind(this)} />
    </View>)
  }
}
